<!DOCTYPE html>

<!--
Copyright 2014 Intel Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<html>
<head>
    <title>WebRTC Sample</title>
</head>
<body onload="start()" onunload="stop()">
    <span id="outputtext"></span>
    <hr />
    <textarea id="inputtext" style="width:100%" onkeypress="onUserKeyPressEvent(event)"></textarea>
    <script type="text/javascript">
        var connection = null;
        var datachannel = null;
        var configuration = { "iceServers": [/*{{{ICESERVERS}}}*/] };
        var currentoffer = null;
        var requester;
        var sdp = "";
        var outputtextbox = document.getElementById("outputtext");
        var inputtextbox = document.getElementById("inputtext");
        var remoteSDP = "/*{{{SDP}}}*/";

        function stop() { connection.close(); }

        function start() {
            msg("Starting...");

            if (typeof mozRTCPeerConnection !== 'undefined') { connection = new mozRTCPeerConnection(configuration); }
            else if (typeof RTCPeerConnection !== 'undefined') { connection = new RTCPeerConnection(configuration); }
            else if (typeof webkitRTCPeerConnection !== 'undefined') { connection = new webkitRTCPeerConnection(configuration); }
            else return false;

            connection.ondatachannel = onNewDataChannel;
            connection.onicecandidate = onIceCandidate;
            connection.oniceconnectionstatechange = function ()
            {
                if (connection.iceConnectionState == 'disconnected') {
                    msg('DISCONNECTED');
                    alert('This session has closed!');
                    window.close();
                }
            }


            var ax;
            var rSDP = window.atob(remoteSDP);

            //setTimeout(function () {
                if (typeof mozRTCSessionDescription !== 'undefined') { ax = new mozRTCSessionDescription({ type: "offer", sdp: rSDP }) } else { ax = new RTCSessionDescription({ type: "offer", sdp: rSDP }) }
                connection.setRemoteDescription(ax, onSetRemoteDescriptionDone, onError);
            //}, 2000);
            //alert(rSDP);
            
            
        }

        function onNewDataChannel(e)
        {
            msg("Connected.");
            msg("Channel [" + e.channel.label + "] created");
            datachannel = e.channel;
            datachannel.onmessage = function (event) { msg("Remote: " + event.data); }            
        }
        function onUserKeyPressEvent(event) {
            if (event.keyCode == 13) {
                datachannel.send(inputtextbox.value);
                msg("Local: " + inputtextbox.value);
                inputtextbox.value = "";
                if (e.preventDefault) e.preventDefault();
                if (e.stopPropagation) e.stopPropagation();
                return false;
            }
        }

        function onIceCandidate(e) {
            if (e.candidate == null) {
                if (sdp == "") {
                    msg("SDP ERROR!");
                    return;
                }
                msg('Posting WebRTC offer...');
                requester = new XMLHttpRequest();
                requester.onload = initiatorResponse;
                requester.onerror = initiatorErrorResponse;
                requester.open("POST", window.location.protocol + "//" + window.location.host, true);
                requester.send(sdp);
                
                return;
            }
            currentoffer.sdp += ("a=" + e.candidate.candidate + "\r\n");
            sdp = currentoffer.sdp;
        }

        function onCandidateAdded(e) { debug('onCandidateAdded: ' + e); }

        function onSetLocalDescriptionDone() { }

        function initiatorResponse() {
            if (requester.status != 200) {
                msg('ERROR: ' + requester.status);
                return;
            }
        }

        function initiatorErrorResponse() { msg('Could not contact server.'); }

        function onSetRemoteDescriptionDone()
        {
            connection.createAnswer(onAnswerDone, onError);
        }
        function onAnswerDone(answer) {
            currentoffer = answer;
            sdp = currentoffer.sdp;

            connection.setLocalDescription(answer, onSetLocalDescriptionDone, onError);
            currentanswer = answer;
        }
        function stop() { connection.close(); }
        function onError(e) { if (e.message) alert("onError: " + e.message); else alert(e); }
        function debug(m) { /* console.log(m); */ }
        function msg(m) { outputtextbox.innerHTML += (m + "<br />"); }

    </script>
</body>
</html>